package com.framework.boc.admin.utils;

import com.framework.boc.admin.interceptor.BocRestHttpRequestInterceptor;
import com.framework.boc.error.CommonException;
import com.framework.boc.error.ErrorEnum;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Map;

@Service
public class BocRestUtil {

    String baseUrl = "http://amr.nmg.gov.cn:27001";

//    @Autowired
    RestTemplate restTemplate;

    @PostConstruct
    private void init() {
        restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add(new BocRestHttpRequestInterceptor());
    }


    /**
     * 发送get请求
     * @param path      相对路径
     * @param clazz     请求对象类型
     * @param <T>       对象类型
     * @return          对象
     */
    public <T> T get(String path, Class<T> clazz) throws CommonException {
        String url = baseUrl + path;
        ResponseEntity<T> entity = restTemplate.getForEntity(url, clazz);
        if (entity.getStatusCode().equals(HttpStatus.OK)) {
            return entity.getBody();
        }
        throw new CommonException(ErrorEnum.UNKNOW_ERROR, entity.getStatusCode().toString());
    }


    /**
     * 发送post请求
     * @param path      请求路径
     * @param clazz     返回对象类型
     * @param data      请求参数
     * @param <T>       返回对象类型
     * @return          对象
     */
    public <T> T post(String path, Class<T> clazz, Map<String, Object> data) throws CommonException {
        String url = baseUrl + path;
        ResponseEntity<T> response = restTemplate.postForEntity(url, null, clazz, data);
        if (response.getStatusCode().equals(HttpStatus.OK)) {
            return response.getBody();
        }
        throw new CommonException(ErrorEnum.UNKNOW_ERROR, response.getStatusCode().toString());
    }



}
